package Domain.MySqlAccessors;

import Domain.Actor;
import Domain.Exceptions.NoActorsException;
import Persistance.MySqlUtilityManagment;
import Persistance.PrintfFormat;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;
import java.util.StringTokenizer;

/**
 * Accessors to the actors table.
 */
public class MySqlActorProxy extends MySqlProxy<Actor> {

    public MySqlActorProxy(MySqlUtilityManagment sql) {
        super(sql);
        TABLE_NAME = "actors";
        KEY_COLUMN_NAME = "id=%s";
        ALL_COLUMN_NAMES = "firstname, lastname";
    }

    public Actor toRecordType(ResultSet rs) throws SQLException {
        long actorId = (Long) rs.getObject("id");
        String firstname = (String) rs.getObject("firstname");
        String lastname = (String) rs.getObject("lastname");
        return new Actor(actorId, firstname, lastname);
    }

    public String toValues(Actor actor) {
        Object[] values = {actor.getFirstname(),actor.getLastname()};
        return new PrintfFormat("'%s','%s'").sprintf(values);
    }

    /**
     * this method get the ID of an actor according to his name
     * @param actorname firstname+second
     * @return ID of the actor
     * @throws Domain.Exceptions.NoActorsException -movie with no actors asociated
     */
    public int getRecordByName(String actorname) throws NoActorsException {
        StringTokenizer token = new StringTokenizer(actorname, " ");
        int count = token.countTokens();
        if(count==0)
            throw new NoActorsException();

        String filter="";
        if (token.countTokens()>1){
            filter= "actors.firstname=\""+ token.nextToken()+ "\" AND actors.lastname=\""+ token.nextToken() +"\" " ;
        }
        else {
            filter = "actors.firstname=\"" + token.nextToken()+"\" ";
        }
        Collection<Actor> id = searchRecords(filter);
        if( id.size()==0)
            throw new NoActorsException();
        return (int) id.iterator().next().getId();
    }
}
